package org.example.web;

import org.example.dto.TaskDto;
import org.example.utils.AjaxResult;
import org.example.utils.QuartzUtils;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/job")
public class JobController {
    @Autowired
    private SchedulerFactoryBean factoryBean;


    @GetMapping("/starttask")
    public AjaxResult startTask() {
        QuartzUtils.startJobs(factoryBean.getScheduler());
        return AjaxResult.success("开启成功");
    }

    @PostMapping("/modifytask")
    public AjaxResult modifyTask(@RequestBody TaskDto taskDto) {
        Scheduler sched = factoryBean.getScheduler();
        QuartzUtils.modifyJobTime(sched, taskDto.getTaskName(), taskDto.getCron());
        return AjaxResult.success("更新成功");
    }

    @PostMapping("/addtask")
    public AjaxResult addTask(@RequestBody TaskDto taskDto) throws ClassNotFoundException {
        Scheduler sched = factoryBean.getScheduler();
        QuartzUtils.addJob(sched, taskDto.getTaskName(), Class.forName(taskDto.getClassName()), null, taskDto.getCron());
        return AjaxResult.success("创建成功");
    }

    @GetMapping("/deltask/{taskName}")
    public AjaxResult delTask(@PathVariable("taskName") String taskName) {
        Scheduler sched = factoryBean.getScheduler();
        QuartzUtils.removeJob(sched, taskName);
        return AjaxResult.success("删除成功");
    }
}
